package basis

import (
	"cubeAdmin/common"
	"cubeAdmin/common/initialize"
	"cubeAdmin/common/jwtauth"
	"cubeAdmin/common/utils"
	"cubeAdmin/controllers"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
)

// IoController 用于处理文件上传和下载的公共服务
type IoController struct {
	controllers.BaseController
}

// Index 获取部门列表视图
// @router /index [get]
func (c *IoController) Index() {
	c.Data["pageTitle"] = "文件上传"
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.TplName = "system/file/demo.tpl"
}

// Upload @Title 文件上传
// @Description 文件上传
// @Success 200 {object} controllers.Result
// @router /upload [post]
func (c *IoController) Upload() {
	/*files, err := c.GetFiles("myfiles")
	if err != nil {
		http.Error(w, err.Error(), http.StatusNoContent)
		return
	}
	for i, _ := range files {
		//for each fileheader, get a handle to the actual file
		file, err := files[i].Open()
		defer file.Close()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}*/

	file, header, err := c.GetFile("file")
	fmt.Println(err)

	headerOtc := map[string]string{
		//"Content-Type": "application/octet-stream",
		"Content-Type": "multipart/form-data",
		//"Region":       "s-east-1",
	}

	upload, e := initialize.Minio.Upload(file, header, headerOtc)
	if e != nil {
		logs.Error(e.Error())
	}

	if e != nil {
		c.Fail("上传失败", common.MsgErr)
	} else {
		c.Ok(upload)
	}
}

// GetSignURL 通过对象名获取访问链接
// @Title 通过对象名获取访问链接
// @router /sign/:id [get]
func (c *IoController) GetSignURL() {
	id := c.Ctx.Input.Param(":id")
	url, err := initialize.Minio.GetSignURL(id, 120)
	remote, err := utils.GetRemote("http://" + url)
	if err != nil {
		logs.Error(err.Error())
	}
	c.Ctx.WriteString(string(remote))
}
